package org.glut.backend.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.glut.backend.domain.LoginResult;
import org.glut.backend.domain.RegisterResult;
import org.glut.backend.domain.User;
import org.glut.backend.service.IUserService;
import org.glut.backend.util.AliOSSUtils;
import org.glut.backend.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 用户表 前端控制器
 *
 * @author gluglu2
 * @since 2025-08-02 14:30
 */
@RestController
@Slf4j
public class UserController {
    @Autowired
    private IUserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private AliOSSUtils aliOSSUtils;

    /**
     * @param user
     * @return org.springframework.http.ResponseEntity<org.glut.backend.domain.User>
     * @description: 用户密码登录
     * @author: gluglu2
     * @date: 2025/8/4 10:41
     */
    @PostMapping("/User/PasswordLogin")
    public ResponseEntity<LoginResult> passwordLogin(@RequestBody User user) {
        LoginResult resp = userService.passwordLogin(user.getPhone(), user.getPassword());

        if (resp.getCode() == 0) {

            String token = jwtUtil.generateToken(resp.getUser().getId());

            // Token放在请求头中
            return ResponseEntity.ok()
                    .header("Authorization", "Bearer " + token)
                    .body(resp);
        } else {
            return ResponseEntity.ok().body(resp);
        }
    }

    /**
     * @param user
     * @return org.springframework.http.ResponseEntity<org.glut.backend.domain.LoginResult>
     * @description: 用户短信登录
     * @author: gluglu2
     * @date: 2025/8/6 16:42
     */

    @PostMapping("/User/SmsLogin")
    public ResponseEntity<LoginResult> smsLogin(@RequestBody User user) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone, user.getPhone());
        User respUser = userService.getOne(queryWrapper);

        // 用户不存在
        if (respUser == null) {
            LoginResult errorResp = new LoginResult();
            errorResp.setCode(1);
            errorResp.setMsg("用户不存在");
            return ResponseEntity.ok().body(errorResp);
        }

        // 成功响应
        LoginResult successResp = new LoginResult();
        successResp.setCode(0);
        successResp.setMsg("登录成功");
        successResp.setUser(respUser);

        // 生成Token并返回
        String token = jwtUtil.generateToken(respUser.getId());
        return ResponseEntity.ok()
                .header("Authorization", "Bearer " + token)
                .body(successResp);
    }

    /**
     * @param user
     * @return org.springframework.http.ResponseEntity<org.glut.backend.domain.RegisterResult>
     * @description: 用户注册
     * @author: gluglu2
     * @date: 2025/8/6 16:42
     */
    @PostMapping("/User/Register")
    public ResponseEntity<RegisterResult> register(@RequestBody User user) {
        // 检查手机号唯一性
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone, user.getPhone());
        if (userService.getOne(queryWrapper) != null) {
            RegisterResult errorResp = new RegisterResult();
            errorResp.setCode(1);
            errorResp.setMsg("用户已存在");
            return ResponseEntity.ok().body(errorResp);
        }

        // 生成随机用户名，小于6位，自动在前面补零
        String randomUsername = "用户" + String.format("%06d", (int) (Math.random() * 1000000));
        user.setUsername(randomUsername);

        if (userService.save(user)) {
            User respUser = userService.getOne(queryWrapper);

            RegisterResult successResp = new RegisterResult();
            successResp.setCode(0);
            successResp.setMsg("注册成功");
            successResp.setUser(respUser);

            // 生成Token
            String token = jwtUtil.generateToken(respUser.getId());
            return ResponseEntity.ok()
                    .header("Authorization", "Bearer " + token)
                    .body(successResp);
        }

        RegisterResult errorResp = new RegisterResult();
        errorResp.setCode(2);
        errorResp.setMsg("注册失败");
        return ResponseEntity.internalServerError().body(errorResp);
    }

    /**
     * @param userId
     * @return org.springframework.http.ResponseEntity<org.glut.backend.domain.User>
     * @description: 查询用户信息
     * @author: gluglu2
     * @date: 2025/8/6 16:49
     */
    @GetMapping("/User/GetUserInfo")
    public ResponseEntity<User> getUserInfo(@RequestParam Integer userId) {
        return ResponseEntity.ok().body(userService.getById(userId));
    }

    /**
     * @param user
     * @return org.springframework.http.ResponseEntity<org.glut.backend.domain.User>
     * @description: 更新用户信息
     * @author: gluglu2
     * @date: 2025/8/7 21:44
     */
    @PostMapping("/User/UpdateUserInfo")
    public ResponseEntity<User> updateUserInfo(@RequestBody User user) {
        if (userService.updateById(user)) {
            User respUser = userService.getById(user.getId());
            return ResponseEntity.ok().body(respUser);
        }

        return ResponseEntity.badRequest().body(null);
    }

    /**
     * 更新用户头像
     *
     * @param image 前端上传的文件
     * @return 统一返回结果
     * @throws IOException
     */
    @PostMapping("/User/UploadAvatar")
    public ResponseEntity<String> upload(Integer userId, MultipartFile image) throws IOException {
        log.info("文件上传，文件名：{}", image.getOriginalFilename());

        String url = aliOSSUtils.upload(image);
        log.info("文件上传完成，访问URL：{}", url);

        User user = new User();
        user.setId(userId);
        user.setAvatar(url);

        if (userService.updateById(user)) {
            return ResponseEntity.ok().body("头像更新成功");
        } else {
            return ResponseEntity.badRequest().body("头像更新失败");
        }
    }

}
